package com.zzyl.service.impl;

import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.http.Method;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.zzyl.enums.BasicEnum;
import com.zzyl.exception.BaseException;
import com.zzyl.service.WeChatService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class WeChatServiceImpl implements WeChatService {
    private static final String PHONE_URL = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=";
    private static final String ACCESS_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token";
    private static final String OPENID_URL = "https://api.weixin.qq.com/sns/jscode2session";

    @Value("${zzyl.wechat.appid}")
    private String appid;

    @Value("${zzyl.wechat.secret}")
    private String secret;

    @Override
    public String getPhoneNumber(String code) {
        Map map = new HashMap();
        map.put("code",code);
        String post = HttpUtil.post(PHONE_URL+getAccessToken(), JSONUtil.toJsonStr(map));
        if(JSONUtil.parseObj(post).getInt("errcode") != 0){
            throw new RuntimeException(JSONUtil.parseObj(post).getStr("errmsg"));
        }
        String phone = JSONUtil.parseObj(post).getJSONObject("phone_info").getStr("phoneNumber");
        return phone;
    }

    @Override
    public String getAccessToken() {
        Map loginInfo = getLoginInfo();
        loginInfo.put("grant_type","client_credential");
        HttpResponse execute = HttpUtil.createRequest(Method.GET, ACCESS_TOKEN_URL).form(loginInfo).execute();
        JSONObject entries = JSONUtil.parseObj(execute.body());
        if(entries.get("errcode") != null){
            throw new RuntimeException(entries.getStr("errmsg"));
        }
        return entries.getStr("access_token");
    }

    @Override
    public String getOpenId(String code) {
        Map loginInfo = getLoginInfo();
        loginInfo.put("js_code",code);
        loginInfo.put("grant_type","authorization_code");
        HttpResponse execute = HttpUtil.createRequest(Method.GET, OPENID_URL).form(loginInfo).execute();
        String body = execute.body();
        JSONObject entries = JSONUtil.parseObj(body);
        if(entries.get("errcode") != null){
            throw new RuntimeException(entries.getStr("errmsg"));
        }
        String openid = entries.getStr("openid");
        return openid;
    }


    private Map getLoginInfo(){
        Map map = new HashMap();
        map.put("appid",appid);
        map.put("secret",secret);
        return map;
    }
}
